"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var icons_1 = require("@ant-design/icons");
var umi_1 = require("umi");
// @ts-ignore
var antd_1 = require("antd");
var react_1 = require("react");
var pro_layout_1 = require("@ant-design/pro-layout");
// @ts-ignore
var pro_table_1 = require("@ant-design/pro-table");
var baseService_1 = require("@/assets/service/baseService");
var service_1 = require("@/pages/report/SourceList/service");
var lib_1 = require("@ant-design/icons/lib");
var react_codemirror_1 = require("@uiw/react-codemirror");
require("codemirror/theme/3024-day.css");
require("codemirror/addon/selection/active-line");
var modulesUrl_1 = require("@/assets/constant/modulesUrl");
var utils_1 = require("@/assets/utils/utils");
var service_2 = require("./service");
var FormItem_1 = require("antd/es/form/FormItem");
require('codemirror/addon/hint/show-hint.css'); // 用来做代码提示
require('codemirror/addon/hint/show-hint.js'); // 用来做代码提示
require('codemirror/addon/hint/sql-hint.js'); // 用来做代码提示
var TableList = function () {
    var sourceSelectList = umi_1.useRequest(function () { return baseService_1.listForSelect(modulesUrl_1.modulesUrl.reportSource); }).data;
    var _a = react_1.useState([]), sourceTree = _a[0], setSourceTree = _a[1];
    var _b = react_1.useState([]), columns = _b[0], setColumns = _b[1];
    var _c = react_1.useState([]), tableData = _c[0], setTableData = _c[1];
    /**
     * 用于保存的数据
     */
    var _d = react_1.useState({
        sql: "select * from report_source where id = $id$;",
        name: "",
        sourceId: "",
        description: "",
        variables: [{ title: "查询", name: "id", type: "1" }]
    }), saveData = _d[0], setSaveData = _d[1];
    /**
     * 变量弹框参数
     */
    var _e = react_1.useState({
        // 是否显示
        visible: false,
        // 是否是添加
        isAdd: true,
    }), variableModel = _e[0], setVariableModel = _e[1];
    /**
     * 变量弹框form实例
     */
    var variableForm = antd_1.Form.useForm()[0];
    /**
     * 执行sql线程
     */
    var executeSqlRun = umi_1.useRequest(function () { return service_2.executeSql(saveData); }, {
        manual: true,
        onSuccess: function (result, params) {
            // 组装表格表头
            var columnList = [];
            result.columns.forEach(function (column) {
                columnList.push({ title: column.name, dataIndex: column.name, });
            });
            utils_1.hooksSet(setColumns, columnList);
            // 组装表格数据
            utils_1.hooksSet(setTableData, result.resultList);
            // @ts-ignore 关闭弹框信息
            params[0]();
        }
    }).run;
    /**
     * 获取数据库列表的线程
     */
    var getSourceDbsRun = umi_1.useRequest(function (id) { return service_1.getDatabaseNameList({ id: id }); }, {
        manual: true,
        onSuccess: function (result, params) {
            // 组装tree
            if (result && result.length > 0) {
                var sourceTree_1 = [];
                result.forEach(function (n) {
                    sourceTree_1.push({ "title": n, "key": n, "icon": <lib_1.DatabaseOutlined />, "isLeaf": true });
                });
                utils_1.hooksSet(setSourceTree, sourceTree_1);
                // @ts-ignore 第二个参数为关闭弹框的方法
                params[1]();
            }
        }
    }).run;
    /**
     * 加载数据源的数据库列表
     * @param fields
     */
    var selectSource = function (value) { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(this, function (_a) {
            // 启动线程，开始加载
            // @ts-ignore
            getSourceDbsRun(value, antd_1.message.loading('正在加载'));
            utils_1.hooksSet(setSaveData, { sourceId: value });
            return [2 /*return*/];
        });
    }); };
    /**
     * 变量保存提交
     * @param fields
     */
    var variableFormSubmit = function () { return __awaiter(void 0, void 0, void 0, function () {
        var nowVariables, nowVariableFormValues, isSave;
        return __generator(this, function (_a) {
            nowVariables = saveData.variables;
            nowVariableFormValues = variableForm.getFieldsValue();
            isSave = true;
            // 判断是否为添加
            if (variableModel.isAdd) {
                // 如果已有相同变量名则提示
                nowVariables.forEach(function (n) {
                    if (n.name === nowVariableFormValues.name) {
                        antd_1.message.destroy();
                        antd_1.message.error('该变量已存在');
                        isSave = false;
                    }
                });
            }
            if (isSave) {
                // 保存
                nowVariableFormValues.title = "查询";
                nowVariables.push(nowVariableFormValues);
                utils_1.hooksSet(setSaveData, { variables: nowVariables });
                // 重置form
                variableForm.resetFields();
                utils_1.hooksSet(setVariableModel, { visible: false });
            }
            return [2 /*return*/];
        });
    }); };
    return (<pro_layout_1.PageContainer title={"数据视图添加"}>
      <antd_1.Row>
        <antd_1.Col span={4}>
          <antd_1.Space direction={"vertical"} size={"middle"}>
            <antd_1.Input placeholder="请输入名称" onChange={function (e) { return utils_1.hooksSet(setSaveData, { name: e.target.value }); }}/>
            <antd_1.Input placeholder="请输入描述" onChange={function (e) { return utils_1.hooksSet(setSaveData, { description: e.target.value }); }}/>
            <antd_1.Select showSearch placeholder="请选择数据源" optionFilterProp="label" options={sourceSelectList} style={{ width: "100%" }} onSelect={selectSource}/>
            <antd_1.Input.Search placeholder="搜索表/字段名称"/>
            <antd_1.Tree style={{ backgroundColor: "rgb(240,242,245)" }} showIcon treeData={sourceTree}>
            </antd_1.Tree>
          </antd_1.Space>
        </antd_1.Col>
        <antd_1.Divider type="vertical"/>
        <antd_1.Col span={19}>
          <antd_1.Row style={{ height: "200px" }}>
            <antd_1.Col span={18}>
              <react_codemirror_1.default value={saveData.sql} onChange={function (a) { return utils_1.hooksSet(setSaveData, { sql: a.getValue() }); }} options={{
        theme: 'monokai',
        mode: "text/x-mysql",
        styleActiveLine: true
    }}/>
            </antd_1.Col>
            <antd_1.Divider type="vertical"/>
            <antd_1.Col span={5}>
              <div style={{ height: "200px", overflow: "auto" }}>
                <div style={{ fontWeight: "bold" }}>
                  <span>变量</span>
                  <div style={{ float: "right" }}>
                    <antd_1.Button type="text" onClick={function () { return utils_1.hooksSet(setVariableModel, { visible: true }); }}><icons_1.PlusOutlined /></antd_1.Button>
                  </div>
                </div>
                <antd_1.List size="small" dataSource={saveData.variables} renderItem={function (item) {
        return <antd_1.List.Item onClick={function () {
            // 初始化form
            saveData.variables.forEach(function (n) {
                if (n.name === item.name) {
                    variableForm.setFieldsValue(item);
                }
            });
            utils_1.hooksSet(setVariableModel, { visible: true });
        }} style={{ cursor: "pointer" }}>
                      <antd_1.List.Item.Meta title={<span><antd_1.Tag color="green">{item.title}</antd_1.Tag>{item.name}</span>}/>
                    </antd_1.List.Item>;
    }}/>
              </div>
            </antd_1.Col>
          </antd_1.Row>
          <antd_1.Divider />
          <div style={{ padding: "20px", backgroundColor: "white" }}>
            <pro_table_1.default columns={columns} rowKey="key" pagination={{
        showQuickJumper: true,
    }} search={false} dateFormatter="string" options={false} dataSource={tableData} scroll={{ x: true }} toolBarRender={false}/>
          </div>
          <antd_1.Divider />
          <antd_1.Row>
            <antd_1.Col span={19}/>
            <antd_1.Col span={5}>
              <antd_1.Space>
                <antd_1.Button>
                  取消
                </antd_1.Button>
                <antd_1.Button type="primary" onClick={function () {
        // @ts-ignore
        executeSqlRun(antd_1.message.loading('正在执行'));
    }}>执行</antd_1.Button>
                <antd_1.Button>
                  保存
                </antd_1.Button>
              </antd_1.Space>
            </antd_1.Col>
          </antd_1.Row>
        </antd_1.Col>
      </antd_1.Row>
      <antd_1.Modal title={(variableModel.isAdd ? "添加" : "编辑") + "变量"} visible={variableModel.visible} onCancel={function () { return utils_1.hooksSet(setVariableModel, { visible: false }); }} onOk={variableFormSubmit} destroyOnClose>
        <antd_1.Form form={variableForm}>
          <FormItem_1.default label="名称" name="name">
            <antd_1.Input placeholder="名称"/>
          </FormItem_1.default>
          <FormItem_1.default label="类型" name="type" initialValue="string">
            <antd_1.Select placeholder="类型" style={{ width: "100%" }} defaultValue={"string"}>
              <antd_1.Select.Option value="1">字符串</antd_1.Select.Option>
              <antd_1.Select.Option value="2">数字</antd_1.Select.Option>
            </antd_1.Select>
          </FormItem_1.default>
        </antd_1.Form>
      </antd_1.Modal>
    </pro_layout_1.PageContainer>);
};
exports.default = TableList;
